package org.jeecg.modules.flowable.utils.flow;

import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.StartEvent;
import org.flowable.bpmn.model.UserTask;
import org.jeecg.modules.flowable.constant.FlowableTaskConstant;
import org.jeecg.modules.flowable.dto.FlowTaskSettingDTO;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 流程模型自定义拓展工具
 */
public class FlowableModelUtil {

    /**
     * 获取开始节点的拓展参数（默认只取主流第一个开始节点）
     */
    public static String getStartExtension(BpmnModel bpmnModel, String key) {
        // 获取主流程开始节点
        List<StartEvent> startEventList = bpmnModel.getMainProcess().findFlowElementsOfType(StartEvent.class);
        if (CollectionUtils.isEmpty(startEventList)) {
            return null;
        }
        FlowElement flowElement = startEventList.get(0);
        String text = ExtensionElementUtil.elementText(key, flowElement);
        if (StringUtils.isBlank(text)) {
            return null;
        }
        return text;
    }


    /**
     * 获取流程中的节点设置
     */
    public static List<FlowTaskSettingDTO> taskExpandInfo(BpmnModel bpmnModel) {
        // 获取主流程所有用户节点
        List<UserTask> userTaskList = bpmnModel.getMainProcess().findFlowElementsOfType(UserTask.class);
        if (CollectionUtils.isEmpty(userTaskList)) {
            return new ArrayList<>();
        }
        List<FlowTaskSettingDTO> settingList = new ArrayList<>(userTaskList.size());
        userTaskList.forEach(e -> {
            FlowTaskSettingDTO settingDTO = elementSetting(e);
            if (Objects.isNull(settingDTO)) {
                return;
            }
            settingDTO.setActivityId(e.getId());
            settingDTO.setActivityName(e.getName());
            settingList.add(settingDTO);
        });
        return settingList;
    }

    /**
     * 获取节点中存放的参与者数据
     */
    private static FlowTaskSettingDTO elementSetting(FlowElement element) {
        String text = ExtensionElementUtil.elementText(FlowableTaskConstant.TASK_BASE_SETTING, element);
        if (StringUtils.isBlank(text)) {
            return null;
        }
        if (!JSONUtil.isTypeJSON(text)) {
            throw new RuntimeException("请确认导入数据正确，请检查JSON参数");
        }
        return JSONUtil.toBean(text, FlowTaskSettingDTO.class, true);
    }
}
